/*!
 * Copyright (C) 2020 - All Rights Reserved by
 * @author : ZhaoYanbo
 * @email  : zyb920@hotmail.com
 * @created: 2020-10-31
 * @version: 1.0.0.0
 *
 */

#include "cmodelmanager.h"
#include "CScan.h"
#include "CImgProvider.h"
#include "thumbdatamodel.h"

#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QFile>
#include <QtDebug>

CModelManager::CModelManager(QObject *parent) : QObject(parent)
{
    m_pThumbDataModel = new ThumbDataModel(this);
    m_pImgProvider = new CImgProvider;
    m_pScan = new CScan(this);
    connect(m_pScan, &CScan::finished, this, &CModelManager::doScanFinished,   Qt::QueuedConnection);
}

CModelManager::~CModelManager()
{
    delete m_pScan;
    m_pScan = nullptr;

    delete m_pThumbDataModel;
    m_pThumbDataModel = nullptr;

}

void CModelManager::registFuncManager(QQmlApplicationEngine *engine)
{
    engine->addImageProvider("thumb", m_pImgProvider);

    QQmlContext *qml_context = engine->rootContext();
    qml_context->setContextProperty("ModelMgr",     this);
    qml_context->setContextProperty("IconModel",     m_pThumbDataModel);

    qmlRegisterUncreatableType<CScan, 1>( "com.zyb.func", 1, 0, "Scan", "Cannot create");
    qmlRegisterUncreatableType<ThumbDataModel, 1>("com.zyb.func", 1, 0, "ThumbDataModel", "Cannot create");
}

void CModelManager::scan(const QString &path)
{
    if(path.isEmpty()) {
        return;
    }
    else {
        if(path.startsWith("file://"))
            m_pScan->scan(path.mid(7));
        else
            m_pScan->scan(path);
    }
}

ThumbDataModel *CModelManager::dataModel() const
{
    return m_pThumbDataModel;
}

void CModelManager::copy(int index)
{
    if( !m_pThumbDataModel->isValid(index))
        return;
    //获取图片地址
    QString file = m_pThumbDataModel->filePath(index);
    QString fileName = m_pThumbDataModel->fileName(index);
    QFile::copy(file, "/home/zyb/图片/" + fileName);
}

void CModelManager::doScanFinished()
{
    //读取图片信息 异步
    QStringList list = m_pScan->files();
    if(list.isEmpty())
        return;
    m_pThumbDataModel->append(list);
    m_pScan->clear();
}
